package com.kai.auth.util;

import com.kai.admin.data.SourceUser;
import com.kai.auth.data.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 登录用户工具
 * </p>
 *
 * @author weijk
 * @since 2023/6/29
 */
public class LoginUserUtil {

    public static final String LOGIN_USER_HEADER = "Login-User";

    /**
     * 获取用户 id
     *
     * @return 用户id
     */
    public static Long getUserId() {
        LoginUser loginUser = getLoginUser();
        return Objects.isNull(loginUser) ? null : loginUser.getUserId();
    }

    /**
     * 获取登录用户
     *
     * @return 登录用户
     */
    public static LoginUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            return null;
        }

        return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;
    }

    /**
     * 根据 token 获取登录用户
     *
     * @param sourceUser 用户信息
     * @return 登录用户
     */
    public static LoginUser convert(SourceUser sourceUser) {
        if (Objects.isNull(sourceUser)) {
            return null;
        }

        return new LoginUser()
                .setUserId(sourceUser.getUserId())
                .setUsername(sourceUser.getUsername())
                .setAuthorities(sourceUser.getRole()
                        .stream()
                        .map(item -> (GrantedAuthority) () -> item)
                        .collect(Collectors.toList()))
                .setExpirationTime(sourceUser.getExpirationTime());
    }

    /**
     * 设置登录用户
     *
     * @param loginUser 登录用户
     */
    public static void setLoginUser(LoginUser loginUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
